package com.lisen.jdbc;

import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.util.Map;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 此处使用apache的dbcp，你实际Resin环境使用的是什么DataSource就继承它，注意有些连接池是final类，不可被继承，所以尽量使用dbcp做测试。
 * 
 * @author Administrator
 * 
 */
public class MyDataSource extends BasicDataSource {

	/**
	 * 定时器，用来运行Connection记录超时的代理。
	 */
	public final static Timer timer = new Timer(true);
	Log logger = LogFactory.getLog(MyDataSource.class);// log4j的使用就不必说了吧。

	class ProxyConnection implements Connection {// 本dataSource
		// getConnection方法返回的代理Connection对象
		Connection innnerConnection;// 实际的连接池里的连接
		String uuid;
		TimerTask task;

		public ProxyConnection(Connection conn, String uuid) {
			task = new TimerTask() {

				@Override
				public void run() {// 里面的代码是堆栈跟踪用的，所以那么奇怪，自己抛出异常又自己捕捉了。
					try {
						throw new RuntimeException();
					} catch (RuntimeException e) {
						logger.debug(e);// 其实log4j作用不大，只是写习惯了。就加上吧。
						e.printStackTrace();// 这句能清楚的打印出调用堆栈。
					}
				}

			};
			timer.schedule(task, 5000);// 设置其5秒后运行，根据你环境实际情况设置，假如你觉得5秒不够，那就10秒，也就是说10秒还不释放此连接则超时。
			this.innnerConnection = conn;
			this.uuid = uuid;
		}

		public void clearWarnings() throws SQLException {
			this.innnerConnection.clearWarnings();
		}

		public void close() throws SQLException {
			this.task.cancel();// 如果在指定时间内关闭了连接，则取消定时，表示此时调用代码正常关闭了连接，不必跟踪。
			this.innnerConnection.close();
		}

		public void commit() throws SQLException {
			this.innnerConnection.commit();
		}

		@Override
		public Array createArrayOf(String typeName, Object[] elements)
				throws SQLException {
			// TODO Auto-generated method stub
			return this.innnerConnection.createArrayOf(typeName, elements);
		}

		@Override
		public Blob createBlob() throws SQLException {
			// TODO Auto-generated method stub
			return this.innnerConnection.createBlob();
		}

		@Override
		public Clob createClob() throws SQLException {
			// TODO Auto-generated method stub
			return this.innnerConnection.createClob();
		}

		@Override
		public NClob createNClob() throws SQLException {
			// TODO Auto-generated method stub
			return this.innnerConnection.createNClob();
		}

		@Override
		public SQLXML createSQLXML() throws SQLException {
			// TODO Auto-generated method stub
			return this.innnerConnection.createSQLXML();
		}

		@Override
		public Statement createStatement() throws SQLException {
			// TODO Auto-generated method stub
			return this.innnerConnection.createStatement();
		}

		@Override
		public Statement createStatement(int resultSetType,
				int resultSetConcurrency) throws SQLException {
			// TODO Auto-generated method stub
			return this.innnerConnection.createStatement(resultSetType,
					resultSetConcurrency);
		}

		@Override
		public Statement createStatement(int resultSetType,
				int resultSetConcurrency, int resultSetHoldability)
				throws SQLException {
			// TODO Auto-generated method stub
			return this.innnerConnection.createStatement(resultSetType,
					resultSetConcurrency, resultSetHoldability);
		}

		@Override
		public Struct createStruct(String typeName, Object[] attributes)
				throws SQLException {
			// TODO Auto-generated method stub
			return this.innnerConnection.createStruct(typeName, attributes);
		}

		@Override
		public boolean getAutoCommit() throws SQLException {
			// TODO Auto-generated method stub
			return this.innnerConnection.getAutoCommit();
		}

		@Override
		public String getCatalog() throws SQLException {
			// TODO Auto-generated method stub
			return this.innnerConnection.getCatalog();
		}

		@Override
		public Properties getClientInfo() throws SQLException {
			// TODO Auto-generated method stub
			return this.innnerConnection.getClientInfo();
		}

		@Override
		public String getClientInfo(String name) throws SQLException {
			// TODO Auto-generated method stub
			return this.innnerConnection.getClientInfo(name);
		}

		@Override
		public int getHoldability() throws SQLException {
			// TODO Auto-generated method stub
			return this.innnerConnection.getHoldability();
		}

		@Override
		public DatabaseMetaData getMetaData() throws SQLException {
			// TODO Auto-generated method stub
			return this.innnerConnection.getMetaData();
		}

		@Override
		public int getTransactionIsolation() throws SQLException {
			// TODO Auto-generated method stub
			return this.innnerConnection.getTransactionIsolation();
		}

		@Override
		public Map<String, Class<?>> getTypeMap() throws SQLException {
			// TODO Auto-generated method stub
			return this.innnerConnection.getTypeMap();
		}

		@Override
		public SQLWarning getWarnings() throws SQLException {
			// TODO Auto-generated method stub
			return this.innnerConnection.getWarnings();
		}

		@Override
		public boolean isClosed() throws SQLException {
			// TODO Auto-generated method stub
			return this.innnerConnection.isClosed();
		}

		@Override
		public boolean isReadOnly() throws SQLException {
			// TODO Auto-generated method stub
			return this.innnerConnection.isReadOnly();
		}

		@Override
		public boolean isValid(int timeout) throws SQLException {
			// TODO Auto-generated method stub
			return this.innnerConnection.isValid(timeout);
		}

		@Override
		public String nativeSQL(String sql) throws SQLException {
			// TODO Auto-generated method stub
			return this.nativeSQL(sql);
		}

		@Override
		public CallableStatement prepareCall(String sql) throws SQLException {
			// TODO Auto-generated method stub
			return this.innnerConnection.prepareCall(sql);
		}

		@Override
		public CallableStatement prepareCall(String sql, int resultSetType,
				int resultSetConcurrency) throws SQLException {
			// TODO Auto-generated method stub
			return this.innnerConnection.prepareCall(sql, resultSetType,
					resultSetConcurrency);
		}

		@Override
		public CallableStatement prepareCall(String sql, int resultSetType,
				int resultSetConcurrency, int resultSetHoldability)
				throws SQLException {
			// TODO Auto-generated method stub
			return this.innnerConnection.prepareCall(sql, resultSetType,
					resultSetConcurrency, resultSetHoldability);
		}

		@Override
		public PreparedStatement prepareStatement(String sql)
				throws SQLException {
			// TODO Auto-generated method stub
			return this.innnerConnection.prepareStatement(sql);
		}

		@Override
		public PreparedStatement prepareStatement(String sql,
				int autoGeneratedKeys) throws SQLException {
			// TODO Auto-generated method stub
			return this.innnerConnection.prepareStatement(sql,
					autoGeneratedKeys);
		}

		@Override
		public PreparedStatement prepareStatement(String sql,
				int[] columnIndexes) throws SQLException {
			// TODO Auto-generated method stub
			return this.innnerConnection.prepareStatement(sql, columnIndexes);
		}

		@Override
		public PreparedStatement prepareStatement(String sql,
				String[] columnNames) throws SQLException {
			// TODO Auto-generated method stub
			return this.innnerConnection.prepareStatement(sql, columnNames);
		}

		@Override
		public PreparedStatement prepareStatement(String sql,
				int resultSetType, int resultSetConcurrency)
				throws SQLException {
			// TODO Auto-generated method stub
			return this.innnerConnection.prepareStatement(sql, resultSetType,
					resultSetConcurrency);
		}

		@Override
		public PreparedStatement prepareStatement(String sql,
				int resultSetType, int resultSetConcurrency,
				int resultSetHoldability) throws SQLException {
			// TODO Auto-generated method stub
			return this.innnerConnection.prepareStatement(sql, resultSetType,
					resultSetConcurrency, resultSetHoldability);
		}

		@Override
		public void releaseSavepoint(Savepoint savepoint) throws SQLException {
			// TODO Auto-generated method stub
			this.innnerConnection.releaseSavepoint(savepoint);
		}

		@Override
		public void rollback() throws SQLException {
			// TODO Auto-generated method stub
			this.innnerConnection.rollback();
		}

		@Override
		public void rollback(Savepoint savepoint) throws SQLException {
			// TODO Auto-generated method stub
			this.innnerConnection.rollback(savepoint);
		}

		@Override
		public void setAutoCommit(boolean autoCommit) throws SQLException {
			// TODO Auto-generated method stub
			this.innnerConnection.setAutoCommit(autoCommit);
		}

		@Override
		public void setCatalog(String catalog) throws SQLException {
			// TODO Auto-generated method stub
			this.innnerConnection.setCatalog(catalog);
		}

		@Override
		public void setClientInfo(Properties properties)
				throws SQLClientInfoException {
			// TODO Auto-generated method stub
			this.innnerConnection.setClientInfo(properties);
		}

		@Override
		public void setClientInfo(String name, String value)
				throws SQLClientInfoException {
			// TODO Auto-generated method stub
			this.innnerConnection.setClientInfo(name, value);
		}

		@Override
		public void setHoldability(int holdability) throws SQLException {
			// TODO Auto-generated method stub
			this.innnerConnection.setHoldability(holdability);
		}

		@Override
		public void setReadOnly(boolean readOnly) throws SQLException {
			// TODO Auto-generated method stub
			this.innnerConnection.setReadOnly(readOnly);
		}

		@Override
		public Savepoint setSavepoint() throws SQLException {
			// TODO Auto-generated method stub
			return this.innnerConnection.setSavepoint();
		}

		@Override
		public Savepoint setSavepoint(String name) throws SQLException {
			// TODO Auto-generated method stub
			return this.innnerConnection.setSavepoint(name);
		}

		@Override
		public void setTransactionIsolation(int level) throws SQLException {
			// TODO Auto-generated method stub
			this.innnerConnection.setTransactionIsolation(level);
		}

		@Override
		public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
			// TODO Auto-generated method stub
			this.innnerConnection.setTypeMap(map);
		}

		@Override
		public boolean isWrapperFor(Class<?> iface) throws SQLException {
			// TODO Auto-generated method stub
			return this.innnerConnection.isWrapperFor(iface);
		}

		@Override
		public <T> T unwrap(Class<T> iface) throws SQLException {
			// TODO Auto-generated method stub
			return this.innnerConnection.unwrap(iface);
		}

		// .....此处省略其他Connection接口的方法没有列出来。你自己必须实现它们，
		// 方法内部只有一句：this.innnerConnection.xxx()；
	}

	// 下面是DataSource接口仅有的两个返回Connection对象的方法。都需要覆盖掉，使得返回代理的Connection
	@Override
	public Connection getConnection() throws SQLException {

		Connection conn = super.getConnection();
		return new ProxyConnection(conn, java.util.UUID.randomUUID().toString());
	}

	@Override
	public Connection getConnection(String user, String password)
			throws SQLException {
		Connection conn = super.getConnection(user, password);
		if (conn instanceof ProxyConnection)
			return conn;
		return new ProxyConnection(conn, java.util.UUID.randomUUID().toString());
	}

}